package www.yingdi365.com.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.HttpHeaders;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.Response;
import www.yingdi365.com.R;
import www.yingdi365.com.base.ZjbBaseActivity;
import www.yingdi365.com.constant.Constant;
import www.yingdi365.com.customview.GridView4ScrollView;
import www.yingdi365.com.model.AppMicrofacies;
import www.yingdi365.com.model.MusicsBean;
import www.yingdi365.com.model.OkObject;
import www.yingdi365.com.util.GsonUtils;
import www.yingdi365.com.util.LogUtil;
import www.yingdi365.com.util.PicassoImageLoader;

public class BianJiWXBActivity extends ZjbBaseActivity implements View.OnClickListener {

    private GridView4ScrollView gridView;
    private AppMicrofacies microfaciesBean;
    private List<AppMicrofacies.PictureListBean> pictureList = new ArrayList<>();
    private List<AppMicrofacies.PictureListBean> pictureListYuanBen = new ArrayList<>();
    private List<AppMicrofacies.PictureListBean> pictureListAdd= new ArrayList<>();
    private TextView textYingYueMZ;
    private TextView textName;
    private TextView textDescribe;
    private MyAdapter adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bian_ji_wxb);
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PicassoImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(false);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(9);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(500);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(500);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
        imagePicker.setMultiMode(true);
        init();
    }

    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        microfaciesBean = (AppMicrofacies) intent.getSerializableExtra(Constant.INTENT_KEY.MicrofaciesBean);
        pictureListYuanBen = microfaciesBean.getPictureList();
        pictureList.addAll(pictureListYuanBen);
    }

    @Override
    protected void findID() {
        gridView = (GridView4ScrollView) findViewById(R.id.gridView);
        textYingYueMZ = (TextView) findViewById(R.id.textYingYueMZ);
        textName = (TextView) findViewById(R.id.textName);
        textDescribe = (TextView) findViewById(R.id.textDescribe);
    }

    @Override
    protected void initViews() {
        ((TextView) findViewById(R.id.textViewTitle)).setText("编辑微相本");
        adapter = new MyAdapter();
        gridView.setAdapter(adapter);
        textYingYueMZ.setText(microfaciesBean.getMusic().getFile().getName());
        textName.setText(microfaciesBean.getName());
        textDescribe.setText(microfaciesBean.getDescribe());
    }

    @Override
    protected void setListeners() {
        findViewById(R.id.imageBack).setOnClickListener(this);
        findViewById(R.id.viewBeiJingYY).setOnClickListener(this);
        findViewById(R.id.viewWeiXiangBenBT).setOnClickListener(this);
        findViewById(R.id.buttonBaoCun).setOnClickListener(this);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Constant.REQUEST_RESULT_CODE.XiuGaiYingYue && resultCode == Constant.REQUEST_RESULT_CODE.XiuGaiYingYue) {
            MusicsBean musicsBean = (MusicsBean) data.getSerializableExtra(Constant.INTENT_KEY.music);
            microfaciesBean.setMusic(musicsBean);
            textYingYueMZ.setText(microfaciesBean.getMusic().getFile().getName());
        }
        if (requestCode == Constant.REQUEST_RESULT_CODE.XiuGaiMingZi && resultCode == Constant.REQUEST_RESULT_CODE.XiuGaiMingZi) {
            String name = data.getStringExtra(Constant.INTENT_KEY.Name);
            String des = data.getStringExtra(Constant.INTENT_KEY.Des);
            microfaciesBean.setName(name);
            microfaciesBean.setDescribe(des);
            textName.setText(microfaciesBean.getName());
            textDescribe.setText(microfaciesBean.getDescribe());
        }
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == Constant.REQUEST_RESULT_CODE.IMAGE_PICKER) {
                final ArrayList<ImageItem> images = (ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS);
                for (int i = 0; i < images.size(); i++) {
                    pictureListAdd.add(new AppMicrofacies.PictureListBean(images.get(i).path));
                }
                pictureList.addAll(pictureListAdd);
                adapter.notifyDataSetChanged();
//                showLoadingDialog();
//                OkObject okObject = getOkObject1();
//                OkGo.get(okObject.getUrl())//
//                        .tag(this)//
//                        .headers(okObject.getHeaders())
//                        .execute(new StringCallback() {
//                            @Override
//                            public void onSuccess(String s, Call call, Response response) {
//                                cancelLoadingDialog();
//                                LogUtil.LogShitou("SheZhiActivity--onSuccess", "获取Qiniu上传访问授权信息" + s);
//                                try {
//                                    showLoadingDialog();
//                                    final AppQiniuToken appQiniuToken = GsonUtils.parseJSON(s, AppQiniuToken.class);
//                                    Configuration config = new Configuration.Builder()
//                                            .chunkSize(512 * 1024)        // 分片上传时，每片的大小。 默认256K
//                                            .putThreshhold(1024 * 1024)   // 启用分片上传阀值。默认512K
//                                            .connectTimeout(10)           // 链接超时。默认10秒
//                                            .useHttps(true)               // 是否使用https上传域名
//                                            .responseTimeout(60)          // 服务器响应超时。默认60秒
//                                            .zone(FixedZone.zone0)        // 设置区域，指定不同区域的上传域名、备用域名、备用IP。
//                                            .build();
//
//                                    // 重用uploadManager。一般地，只需要创建一个uploadManager对象
//                                    UploadManager uploadManager = new UploadManager(config);
//                                    String key = "touxiang" + System.currentTimeMillis() + ".png";
//                                    String token = appQiniuToken.getUptoken();
//                                    uploadManager.put(new File(images.get(0).path), key, token,
//                                            new UpCompletionHandler() {
//                                                @Override
//                                                public void complete(String key, ResponseInfo info, JSONObject res) {
//                                                    cancelLoadingDialog();
//                                                    //res包含hash、key等信息，具体字段取决于上传策略的设置
//                                                    if (info.isOK()) {
//                                                        LogUtil.LogShitou("SheZhiActivity--complete", "成功");
//                                                        LogUtil.LogShitou("SheZhiActivity--complete", "返回信息" + res.toString());
//                                                        QiNiu qiNiu = GsonUtils.parseJSON(res.toString(), QiNiu.class);
//                                                        String imgUrl = appQiniuToken.getUrl() + "/" + qiNiu.getKey();
//                                                        appUser.setPhoto(imgUrl);
//                                                        BaoCun();
//                                                    } else {
//                                                        LogUtil.LogShitou("SheZhiActivity--complete", "失败" + key);
//                                                        LogUtil.LogShitou("SheZhiActivity--complete", "info  " + info.toString());
//                                                    }
//                                                }
//                                            }, null);
//                                } catch (Exception e) {
//                                    Toast.makeText(SheZhiActivity.this, getResources().getString(R.string.shujuchucuo), Toast.LENGTH_SHORT).show();
//                                }
//                            }
//
//                            @Override
//                            public void onError(Call call, Response response, Exception e) {
//                                super.onError(call, response, e);
//                                cancelLoadingDialog();
//                                Toast.makeText(SheZhiActivity.this, getResources().getString(R.string.qingqiushibai), Toast.LENGTH_SHORT).show();
//                            }
//                        });
            } else {
                Toast.makeText(this, "没有数据", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.buttonBaoCun:
                baoCun();
                break;
            case R.id.viewWeiXiangBenBT:
                intent.setClass(this, BianJiWXBMZActivity.class);
                intent.putExtra(Constant.INTENT_KEY.Name, microfaciesBean.getName());
                intent.putExtra(Constant.INTENT_KEY.Des, microfaciesBean.getDescribe());
                startActivityForResult(intent, Constant.REQUEST_RESULT_CODE.XiuGaiMingZi);
                break;
            case R.id.viewBeiJingYY:
                intent.setClass(this, SheZhiYYActivity.class);
                MusicsBean music = microfaciesBean.getMusic();
                intent.putExtra(Constant.INTENT_KEY.music, music);
                startActivityForResult(intent, Constant.REQUEST_RESULT_CODE.XiuGaiYingYue);
                break;
            case R.id.imageBack:
                finish();
                break;
        }
    }

    private OkObject getOkObject() {
        String url = Constant.HOST + Constant.Url.AppMicrofaciesService + "microfacies/save";
        HttpHeaders headers = new HttpHeaders();
        headers.put(Constant.TOKEN, appLoginResult.getToken());
        HashMap<String, String> params = new HashMap<>();
        return new OkObject(headers, params, url);
    }

    private void baoCun() {
        showLoadingDialog();
        OkObject okObject = getOkObject();
        LogUtil.LogShitou("BianJiWXBActivity--微相本修改对象", GsonUtils.parseObject(microfaciesBean));
        OkGo.post(okObject.getUrl())//
                .tag(this)//
                .headers(okObject.getHeaders())
                .upJson(GsonUtils.parseObject(microfaciesBean))//
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        cancelLoadingDialog();
                        LogUtil.LogShitou("BianJiWXBActivity--微相本修改", s);
                        try {
                            AppMicrofacies appMicrofacies = GsonUtils.parseJSON(s, AppMicrofacies.class);
                            Intent intent = new Intent();
                            intent.setAction(Constant.BROADCASTCODE.WeiXiangCeBaoCun);
                            intent.putExtra(Constant.INTENT_KEY.MicrofaciesBean, appMicrofacies);
                            sendBroadcast(intent);
                        } catch (Exception e) {
                            Toast.makeText(BianJiWXBActivity.this, getResources().getString(R.string.shujuchucuo), Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        super.onError(call, response, e);
                        cancelLoadingDialog();
                        if (response != null) {
                            if (response.code() == 401) {
                                showReLoginDialog();
                            }
                        }
                        Toast.makeText(BianJiWXBActivity.this, getResources().getString(R.string.qingqiushibai), Toast.LENGTH_SHORT).show();
                    }
                });
    }

    class MyAdapter extends BaseAdapter {
        class ViewHolder {
            public ImageView image;
        }

        @Override
        public int getCount() {
            return pictureList.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = LayoutInflater.from(BianJiWXBActivity.this).inflate(R.layout.item_bian_ji_wxb, null);
                holder.image = (ImageView) convertView.findViewById(R.id.image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (position == pictureList.size()) {
                holder.image.setImageResource(R.mipmap.add_pic);
                holder.image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent();
                        intent.setClass(BianJiWXBActivity.this, ImageGridActivity.class);
                        startActivityForResult(intent, Constant.REQUEST_RESULT_CODE.IMAGE_PICKER);
                    }
                });
            } else if (position>pictureListYuanBen.size()-1){
                Glide.with(BianJiWXBActivity.this)
                        .load(pictureList.get(position).getUrl())
                        .placeholder(R.mipmap.ic_empty)
                        .into(holder.image);
            }else {
                Glide.with(BianJiWXBActivity.this)
                        .load(pictureList.get(position).getUrl() + Constant.TuPianYaSuo)
                        .placeholder(R.mipmap.ic_empty)
                        .into(holder.image);
            }
            return convertView;
        }
    }
}
